package com.ruoyi.web.controller.mf178;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.mf178.domain.*;
import com.ruoyi.mf178.service.IMf178CouponTradeService;
import com.ruoyi.mf178.service.IMf178OrderService;
import com.ruoyi.mf178.service.Mf178Api;
import com.ruoyi.mf178.service.IMf178SupplyGoodService;
import com.ruoyi.mf178.service.impl.CouponTradeMcd;
import com.ruoyi.mf178.utils.Mf178Utils;
import com.ruoyi.mf178.utils.SnowflakeIdGenerator;
import com.ruoyi.mf178.vo.Mf178OrderStatus;
import com.ruoyi.mf178.vo.OrderStatus;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 正式环境
 * 主账号
 * （账号:15995815769，ID:443224）
 * 密钥管理
 * Appkey：
 * 8753973019
 * <p>
 * ApSecret：
 * e0bddddd5c7d724d
 * <p>
 * <p>
 * 测试环境的：
 * 主账号
 * （账号:15995815769，ID:453639）
 * 密钥管理
 * Appkey：
 * 05564817019
 * <p>
 * ApSecret：
 * 2598a69d3497d012
 */
@RestController
@Slf4j
@RequestMapping("/mf178")
public class Mf178Controller extends BaseController {

    @Autowired
    Mf178Api mf178Api;
    @Autowired
    IMf178SupplyGoodService supplyGoodService;
    @Autowired
    IMf178OrderService mf178OrderService;
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    CouponTradeMcd couponTradeMcd;

    /**
     * 获取商品（全部）接口
     */
    @GetMapping("/getSupplyGoodManageList")
    @ResponseBody
    public Mf178Response getSupplyGoodManageList(SupplyGoodManageQuery query) {
        return mf178Api.getSupplyGoodManageList(query);
    }

    /**
     * 获取商品（全部）接口,并同步商品信息
     */
    @GetMapping("/getSupplyGoodManageListAndSync")
    @ResponseBody
    public Mf178Response getSupplyGoodManageListAndSync(SupplyGoodManageQuery query) {
        if (query.getB_id() == null) {
            // 不传时默认只同步18	代下单-餐饮
            query.setB_id(18);
        }
        Mf178Response resultJson = mf178Api.getSupplyGoodManageList(query);
        if (resultJson.getCode() != 0) {
            // 查询失败 直接返回，不同步
            return resultJson;
        }
        supplyGoodService.syncGoods(resultJson);
        return resultJson;
    }

    /**
     * 修改商品报价（已供应）接口
     */
    @GetMapping("/editSupplyGoodManageStock")
    @ResponseBody
    public Mf178Response editSupplyGoodManageStock(@RequestBody List<EditGoods> editGoodsList) {
        return mf178Api.editSupplyGoodManageStock(editGoodsList);
    }

    @GetMapping("/merchantPackageInfo")
    @ResponseBody
    public Object merchantPackageInfo(String externalCode) {
        return couponTradeMcd.merchantPackageInfo(externalCode);
    }

    @ApiOperation("代下单-餐饮推单")
    @PostMapping({"/order/submit"})
    @ResponseBody
    public Object OrderSubmit(@RequestBody Mf178SubmitOrder mf178SubmitOrder) {
        log.info("收到mf178订单推送:" + JSONObject.toJSONString(mf178SubmitOrder));
        JSONObject data = new JSONObject();
        data.put("code", "SUCCESS");
        data.put("message", "收单成功");
        //TODO 通过id去数据库查询商品信息
        //TODO 根据订单信息和商品信息，调用外部接口上传卡密
        //TODO 根据生成的结果，返回是都单成功还是收单失败

        Mf178SupplyGood good = supplyGoodService.selectMf178SupplyGoodByGoodsId((long) mf178SubmitOrder.getGoods_id());
        if (good == null) {
            log.error("收单异常，未查询到商品信息，商品id：" + mf178SubmitOrder.getGoods_id());
            data.put("code", "FAIL");
            data.put("message", "收单异常，未查询到商品信息");
            return data;
        }
        if (good.getSupplierService() == null) {
            log.error("商品未配置供应商，请联系管理员，商品id：" + mf178SubmitOrder.getGoods_id());
            data.put("code", "FAIL");
            data.put("message", "商品未配置供应商，请联系管理员");
            return data;
        }
        BigDecimal quotePayment = new BigDecimal(mf178SubmitOrder.getUser_quote_payment());
        BigDecimal payment = new BigDecimal(mf178SubmitOrder.getUser_payment());
        if (quotePayment.multiply(new BigDecimal(mf178SubmitOrder.getNum())).compareTo(payment) != 0) {
            log.error("单价：" + quotePayment);
            log.error("数量：" + mf178SubmitOrder.getNum());
            log.error("总金额：" + payment);
            log.error("总金额不正确");
            data.put("code", "FAIL");
            data.put("message", "总金额不正确");
            return data;
        }
        Mf178Order order = mf178OrderService.selectMf178OrderByExternalOrderNo(String.valueOf(mf178SubmitOrder.getUser_order_id()));
        if (order != null) {
            log.error("订单已收录,传入订单号:" + mf178SubmitOrder.getUser_order_id());
            data.put("code", "FAIL");
            data.put("message", "请勿重复提交相同订单号");
//            data.put("data", order); // 订单信息直接返回。
            return data;
        }
        order = new Mf178Order();
        order.setRawRequest(JSONObject.toJSONString(mf178SubmitOrder));
        SnowflakeIdGenerator idWorker = new SnowflakeIdGenerator(1, 1);
        order.setPlatformOrderNo(idWorker.nextIdStr());
        order.setExternalOrderNo(String.valueOf(mf178SubmitOrder.getUser_order_id()));
        order.setAppKey(mf178SubmitOrder.getApp_key());
        order.setExternalGoodsId(good.getGoodsId());
        order.setExternalGoodsName(good.getGoodsName());
        order.setExternalGoodsCode(good.getExternalCode());
        order.setGoodSupplierService(good.getSupplierService());
        order.setBrandName(good.getSpecName());
        order.setSalePrice(new BigDecimal(mf178SubmitOrder.getUser_payment()));
//        order.setOrderStatus();// 初始订单状态
        int i = mf178OrderService.insertMf178Order(order);
        if (i != 1) {
            log.error("订单信息保存失败");
            data.put("code", "FAIL");
            data.put("message", "订单信息保存失败");
            return data;
        }

        try {
            String platformOrderNo = order.getPlatformOrderNo();
            // 根据 good.getSupplierService() 判断使用哪个实现
            IMf178CouponTradeService service = applicationContext.getBean(good.getSupplierService(), IMf178CouponTradeService.class);
            if (mf178SubmitOrder.getNum() == 1) {
                Mf178TradeResponse tradeResponse = service.couponTrade(good, order);
                if (tradeResponse.isSuccess()) {
                    order.setOrderStatus(OrderStatus.Succeed);// 成功状态
                    order.setSupplierOrderNo(tradeResponse.getData().get(0).getOrderNo());
                    order.setCardNo(tradeResponse.getData().get(0).getCardNo());
                    order.setCardType(tradeResponse.getData().get(0).getCardType());
                    order.setCardPwd(tradeResponse.getData().get(0).getCardPwd());
                    order.setCostPrice(tradeResponse.getData().get(0).getCostPrice());
                } else {
                    order.setOrderStatus(OrderStatus.Failed);// 失败状态
                }
            } else {
                order.setOrderStatus(OrderStatus.Succeed);// 成功状态
                Mf178TradeResponse tradeResponse = service.couponTrade(good, order);
                if (tradeResponse.isSuccess()) {
                    String cardNos = tradeResponse.getData().stream()
                            .map(Mf178TradeResponse.Mf178TradeResponseData::getCardNo)
                            .filter(Objects::nonNull)
                            .collect(Collectors.joining(","));

                    String cardPwd = tradeResponse.getData().stream()
                            .map(Mf178TradeResponse.Mf178TradeResponseData::getCardPwd)
                            .filter(Objects::nonNull)
                            .collect(Collectors.joining(","));

                    order.setSupplierOrderNo(tradeResponse.getData().get(0).getOrderNo());
                    order.setCardType(tradeResponse.getData().get(0).getCardType());
                    order.setCardNo(cardNos);
                    order.setCardPwd(cardPwd);
                } else {
                    order.setOrderStatus(OrderStatus.Failed);// 失败状态
                    order.setCardNo("");
                    order.setCardType("");
                    order.setCardPwd("");
                }
                order.setPlatformOrderNo(platformOrderNo);
            }
        } catch (NoSuchBeanDefinitionException e) {
            log.error("调用couponTrade实现类异常，", e);
            order.setOrderStatus(OrderStatus.Failed);// 失败状态
        }
        mf178OrderService.updateMf178Order(order);

        Mf178Order finalOrder = order;
        (new Thread(() -> {
            try {
                Thread.sleep(50L);
            } catch (InterruptedException var5) {
                throw new RuntimeException(var5);
            }
            Mf178Response result = mf178Api.updateStatus(finalOrder);
            finalOrder.setNotifyResponse(JSONObject.toJSONString(result));
            mf178OrderService.updateMf178Order(finalOrder);
        })).start();
        return data;
    }

    @ApiOperation("代下单-餐饮查单")
    @PostMapping({"/order/query"})
    @ResponseBody
    public Object OrderQuery(@RequestBody Mf178QueryOrder mf178QueryOrder) {
        log.info("收到mf178查询订单请求:" + JSONObject.toJSONString(mf178QueryOrder));
        Mf178OrderResult mf178OrderResult = new Mf178OrderResult();
        mf178OrderResult.setCode(0);
        mf178OrderResult.setMessage("");
        Mf178OrderInfo orderInfo = new Mf178OrderInfo();

        Mf178Order order = mf178OrderService.selectMf178OrderByExternalOrderNo(String.valueOf(mf178QueryOrder.getUser_order_id()));
        if (order == null) {
            orderInfo.setStatus(Mf178OrderStatus.NotExists);
            return mf178OrderResult;
        }
        orderInfo.setStatus(Mf178OrderStatus.GetMf178OrderStatus(order.getOrderStatus()));
        orderInfo.setRsp_info(order.getOrderSummary());
        orderInfo.setRsp_time(String.valueOf(System.currentTimeMillis() / 1000L));
        List<Mf178YsCard> ys_cards = new ArrayList();
        if (!StringUtils.isBlank(order.getCardNo())) {
            String[] cardNos = order.getCardNo().split(",");
            for (int i = 0; i < cardNos.length; i++) {
                Mf178YsCard mf178YsCard = new Mf178YsCard();
                if (order.getCardType() != null) {
                    mf178YsCard.setCard_type(Integer.parseInt(order.getCardType()));// 可能异常，cardType如果不为int的话
                }
                mf178YsCard.setCard_no(cardNos[i]);
                ys_cards.add(mf178YsCard);
            }
        }
        if (!StringUtils.isBlank(order.getCardPwd())) {
            String[] cardPwds = order.getCardPwd().split(",");
            for (int i = 0; i < cardPwds.length; i++) {
                Mf178YsCard mf178YsCard = new Mf178YsCard();
                if (order.getCardType() != null) {
                    mf178YsCard.setCard_type(Integer.parseInt(order.getCardType()));// 可能异常，cardType如果不为int的话
                }
                mf178YsCard.setCard_pwd(cardPwds[i]);
                ys_cards.add(mf178YsCard);
            }
        }
        orderInfo.setYs_cards(ys_cards);
        mf178OrderResult.setData(orderInfo);
        return mf178OrderResult;
    }

    @ApiOperation("代下单-餐饮上报")
    @PostMapping({"/order/notify"})
    public Object notify(String externalOrderNo) {
        Mf178Order order = mf178OrderService.selectMf178OrderByExternalOrderNo(externalOrderNo);
        Mf178Response result = mf178Api.updateStatus(order);
        order.setNotifyResponse(JSONObject.toJSONString(result));
        mf178OrderService.updateMf178Order(order);
        return result;
    }


    /**
     * 作废卡
     */
    @PostMapping("/dropCard")
    public AjaxResult dropCard(@RequestBody List<Mf178Order> mf178Order) {
        return mf178OrderService.dropCard(mf178Order);
    }

    /**
     * 查询同步卡信息
     */
    @PostMapping("/syncCardStatus")
    public AjaxResult syncCardStatus(@RequestBody List<Mf178Order> mf178Order) {
        return mf178OrderService.syncCardStatus(mf178Order);

    }
}
